import datetime
import pytz

import coin.exchange.base.kr_rest.public_client_base as pubcb
import coin.exchange.gopax.kr_rest.native_public_client as npubc
from coin.exchange.gopax.kr_rest.product import GopaxProduct
from coin.proto.coin_market_query_pb2 import (
    ProductKline,
    ProductKlineElement)


class GopaxFeedParser(object):
  @staticmethod
  def parse_native_kline(update_msg, product, kline_period, start_time, end_time):
    klines = update_msg
    kline_group = []
    for kline in klines:
      kline_timestamp = kline[0]
      if kline_timestamp / 10**3 >= start_time.timestamp() and \
         kline_timestamp / 10**3 < end_time.timestamp():
        product_kline = ProductKlineElement(kline_timestamp=int(kline_timestamp * 1e+6),
                                            open=float(kline[3]),
                                            high=float(kline[2]),
                                            low=float(kline[1]),
                                            close=float(kline[4]),
                                            volume=float(kline[5]),
                                            turnover=float(kline[5]*float(kline[4])))
        kline_group.append(product_kline)
    assert len(kline_group) > 0
    period_map = {1:'1m', 5:'5m', 30:'30m', 1440:'1d'}
    kline_period = period_map[kline_period]
    return ProductKline(
        symbol=product.symbol,
        native_symbol=product.native_symbol,
        exchange='Gopax',
        market_type='Spot',
        kline_period=kline_period,
        klines=kline_group,
    )

class GopaxPublicClient(pubcb.PublicClientBase):
  ProductType = GopaxProduct

  def __init__(self):
    self.npubc = npubc.GopaxNativePublicClient()

  def query_history_kline_impl(self, product, kline_period, start_time, end_time):
    native_symbol = product.native_symbol
    start_time = start_time.replace(tzinfo=pytz.UTC)
    end_time = end_time.replace(tzinfo=pytz.UTC)
    update = self.npubc.get_history_kline(
        native_symbol, kline_period, start_time, end_time)
    update.msg = GopaxFeedParser.parse_native_kline(update.msg,
                                                  product,
                                                  kline_period,
                                                  start_time,
                                                  end_time)
    return update

  def query_level_book_impl(self, product):
    raise NotImplementedError("Gopax query level book Not Implemented")

if __name__ == "__main__":
  client = GopaxPublicClient()
  start_time = datetime.datetime(2021, 7, 15).replace(tzinfo=pytz.UTC)
  end_time = datetime.datetime(2021, 7, 15, 23, 59, 59).replace(tzinfo=pytz.UTC)
  print(client.query_history_kline(
      GopaxProduct.FromStr('BTC-KRW'), 1440, start_time, end_time).msg)
